package cn.witsky.rtp2ws.push.retry;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.witsky.rtp2ws.Server;
import cn.witsky.rtp2ws.cache.CallManager;
import cn.witsky.rtp2ws.domain.CallInfo;
import cn.witsky.rtp2ws.util.SystemClock;

public class ReadTask implements Runnable {
	private static Logger logger = LoggerFactory.getLogger(ReadTask.class);
	String callId = "";
	boolean isCaller;
	String filePath = "";
	String  taskId="";
	CallInfo call = null;
	public String getTaskId() {
		return taskId;
	}

	public ReadTask(String callId, boolean isCaller) {
		this.callId = callId;
		this.isCaller = isCaller;
		call=CallManager.getCall(callId);
		taskId=call.getRtp(isCaller).getRtpId();
		filePath = Server.downLoadDir + "/" +call.getRtp(isCaller).getPcmName();
	}

	@Override
	public void run() {

		if (call != null) {
			String rtpSource = "";
			if (isCaller) {
				rtpSource = call.getSrcHost() + ":" + call.getCallerPort();
			} else {
				rtpSource = call.getSrcHost() + ":" + call.getCalledPort();
			}
			logger.info("task:{}开始读取rtp流数据文件:{}",taskId,filePath);
			File file = new File(filePath);
			FileChannel channel = null;
			FileInputStream fileInputStream = null;
			int seq = 0;
			if (file.exists()) {
				try {
//					call.getRtp(isCaller).initWsClient();
					fileInputStream = new FileInputStream(file);
					channel = fileInputStream.getChannel();
					// 分配缓冲区
					ByteBuffer byteBuffer = ByteBuffer.allocate(Server.getPayLoadLen());
					while (true) {
						long start=SystemClock.now();
						byteBuffer.clear();
						// 将 channel数据写到buffer中
						int len = channel.read(byteBuffer);
						if (len == -1) {
							break;
						}
						byte[] bytes=new byte[len];
						byteBuffer.flip();		
						int index = 0;
						while (byteBuffer.hasRemaining()) {
							bytes[index++] = byteBuffer.get();
						}
						logger.debug("task:{} byteBuffer:{} bytes.len:{}",taskId,byteBuffer,bytes.length);
						logger.debug("task:{} bytes:{}",taskId,bytes);
						call.offerMessage(rtpSource, this.isCaller, seq++,bytes);	
						long delayTime=SystemClock.getDelayTime(start);
						TimeUnit.MILLISECONDS.sleep(Server.getWaiTime()-delayTime);
					}
					call.getRtp(isCaller).setFinishTime(SystemClock.now());
					logger.info("task:{}读取的rtp流数据文件:{}结束了",taskId,filePath);
				} catch (Exception e) {
					logger.error("task:"+taskId+"读取rtp流数据文件" + filePath + "出现异常:", e);
				} finally {
					try {
						if (fileInputStream != null) {
							fileInputStream.close();
						}
						if (channel != null) {
							channel.close();
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				this.clearPcm();
				RetryManager.freeRtp(callId);
			}
		}
	}

	public void clearPcm() {
		File file = new File(filePath);
		file.delete();
		logger.info("task:{}清理rtp流数据文件:{}",taskId,filePath);
	}
}
